<?php

class Application_Model_Carton extends Zend_Db_Table_Abstract{
	protected $_name = 'cartones';
	
	public function findById($id){
		$select = $this->select()
			->where("status = 'A' AND id = ?", $id);
			
		$result = $this->fetchAll($select);
		$arrCarton = $result->toArray();
		return $arrCarton;
	}
	
	public function getLast20(){
		$select = $this->select()
			->where("status = 'A'")
			->order('fecha DESC')
			->limit(20);
			
		$result = $this->fetchAll($select);
		$arrCartones = $result->toArray();
		return $arrCartones;
	}
	
	public function getLastCarton(){
		$select = $this->select()
			->where("status = 'A'")
			->order('fecha DESC')
			->limit(1);
			
		$result = $this->fetchAll($select);
		$arrCartones = $result->toArray();
		return $arrCartones[0];
	}

    public function uploadFoto($file){
        $server_dir = $_SERVER["DOCUMENT_ROOT"];
        $foto_dir = $server_dir."/cartones/";

        if(file_exists($foto_dir) && is_writable($foto_dir)){
            if( ( ($file["type"] == "image/gif")
                || ($file["type"] == "image/jpeg")
                || ($file["type"] == "image/pjpeg")
                || ($file["type"] == "image/png") )
                && ($file["size"] < 2000000) ){
                $destination = $foto_dir.$file["name"];

                if(move_uploaded_file($file["tmp_name"], $destination)){
                    return $file["name"];
                }else{
                    error_log("[FOTO_ERROR]".$file['error']." ".$file["name"]);
                    return 0;
                }
            }else{
                error_log("[FOTO_ERROR]no es imagen valida");
                return false;
            }
        }else{
            error_log("[FOTO_ERROR] dir not writable or does not exist");
            return false;
        }
    }

    public function addCarton($titulo, $fecha, $imagen, $status){
        $row = $this->createRow();

        $row->titulo = $titulo;
        $row->fecha = $fecha;
        $row->imagen = $imagen;
        $row->status = $status;

        $row->save();

        $id = $this->_db->lastInsertId();

        return $id;
    }

    public function updateCarton($titulo, $imagen, $id){
        $row = $this->find($id)->current();

        $row->titulo = $titulo;
        if($imagen != ""){
            $row->imagen = $imagen;
        }

        if($row->save()){
            return true;
        }else{
            return false;
        }
    }
}
